// utils/websocket.js

let socket = null
let isConnected = false
let reconnectTimer = null
let userId = null
let msgQueue = []

const WebSocketService = {
	// 初始化连接
	init(id) {
		userId = id
		const url = `ws://127.0.0.1:8081/ws?userId=${userId}`

		if (isConnected) return
		console.log('📡 准备连接 WebSocket')

		socket = uni.connectSocket({
			url: url,
			success: () => console.log('✅ 发起连接请求'),
			fail: err => console.error('❌ 连接失败', err)
		})

		this.bindSocketEvents()
	},

	// 绑定事件
	bindSocketEvents() {
		uni.onSocketOpen(() => {
			isConnected = true
			console.log('✅ WebSocket 已连接')
			this.flushMsgQueue()
		})

		uni.onSocketClose(() => {
			isConnected = false
			console.warn('⚠️ WebSocket 已关闭，准备重连')
			this.reconnect()
		})

		uni.onSocketError(err => {
			isConnected = false
			console.error('❌ WebSocket 错误:', err)
			this.reconnect()
		})

		uni.onSocketMessage(res => {
			console.log('📨 收到消息:', res.data)

			try {
				const data = JSON.parse(res.data)
				if (this.onMessageCallback) {
					this.onMessageCallback(data)
				}
			} catch (e) {
				console.error('JSON解析失败', e)
			}
		})
	},

	// 设置消息监听回调
	onMessage(callback) {
		this.onMessageCallback = callback
	},

	// 主动发送消息
	send(data) {
		const msg = typeof data === 'string' ? data : JSON.stringify(data)
		if (isConnected) {
			uni.sendSocketMessage({
				data: msg,
				success: () => console.log('📤 消息发送成功:', msg),
				fail: err => console.error('❌ 消息发送失败:', err)
			})
		} else {
			console.warn('🕓 当前未连接，消息已放入队列')
			msgQueue.push(msg)
		}
	},

	// 刷新队列
	flushMsgQueue() {
		while (msgQueue.length > 0 && isConnected) {
			const msg = msgQueue.shift()
			this.send(msg)
		}
	},

	// 重连机制
	reconnect() {
		if (reconnectTimer) return

		reconnectTimer = setTimeout(() => {
			console.log('🔁 正在尝试重连...')
			this.init(userId)
			reconnectTimer = null
		}, 3000)
	},

	// 关闭连接
	close() {
		if (isConnected) {
			uni.closeSocket()
			isConnected = false
		}
	}
}

export default WebSocketService
